﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using SimpleHttpServer.GuestBook;



namespace SimpleHttpServer
{
    class Worker
    {
        private HttpListenerContext _context;
        private IGuestBook _guestBook;

        public Worker(HttpListenerContext context, IGuestBook guestBook)
        {
            _context = context;
            _guestBook = guestBook;
        }

        public void ProcessRequest()
        {
            if (_context.Request.Url.AbsolutePath == "/Guestbook/")
            {
               ProcessGuestBook();
            }
            else if (_context.Request.Url.AbsolutePath == "/Proxy/")
            {
                ProcessProxy();
            }
            else if (_context.Request.UrlReferrer == null)
            {
                ProcessOther();
            }
            else if (_context.Request.UrlReferrer.AbsolutePath == "/Proxy/")
            {
                string url = _context.Request.UrlReferrer.PathAndQuery;

                url = url.Remove(0, 12);

                ProcessProxy2(url + _context.Request.RawUrl);

            }
            else
            {
                ProcessOther();
            }
        }


        private void ProcessOther()
        {
            string result = "<html><body><h1>" + "Hello world!" + "</h1>";
            DumpTextData(result);
        }


        private void ProcessGuestBook()
        {
            string result = "";

            if (_context.Request.HttpMethod == "GET")
            {
                result = FindAllEntries();
            }
            else if (_context.Request.HttpMethod == "POST")
            {
                StreamReader reader = new StreamReader(_context.Request.InputStream);
                string data = reader.ReadToEnd();

                Dictionary<string, string> dictionary = CommonHelper.CreatePostDictionary(data);

                string user = dictionary["user"];
                string message = dictionary["message"];


                AddNewEntry(new GuestBookEntry(user, message));
                result = FindAllEntries();
            }

            DumpTextData(result);
        }


        private void ProcessProxy2(string url)
        {
            using (WebClient webClient = new WebClient())
            {
                byte[] data = webClient.DownloadData(url);

                //Console.WriteLine("PROXY GET" + " " + url);

                _context.Response.ContentLength64 = data.Length;
                _context.Response.OutputStream.Write(data, 0, data.Length);
                _context.Response.OutputStream.Close();
            }
        }

        private void ProcessProxy()
        {
            string query = _context.Request.Url.Query;

            if (query.Length < 6)
            {
                ProcessOther();
                return;
            }

            string url = query.Remove(0, 5);

            using (WebClient webClient = new WebClient())
            {
                byte[] data = webClient.DownloadData(url);

                _context.Response.ContentLength64 = data.Length;
                _context.Response.OutputStream.Write(data, 0, data.Length);
                _context.Response.OutputStream.Close();
            }
        }


        private void DumpTextData(string text)
        {
            byte[] b = Encoding.UTF8.GetBytes(text);
            _context.Response.ContentLength64 = b.Length;
            _context.Response.OutputStream.Write(b, 0, b.Length);
            _context.Response.OutputStream.Close();
        }

        private void AddNewEntry(GuestBookEntry guestBookEntry)
        {
            _guestBook.Add(guestBookEntry);
        }

        private string FindAllEntries()
        {
            var entries = _guestBook.FindAll();

            return HtmlFormatter.CreateTable(entries);
        }
    }
  
}
